package com.atguigu.yygh.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.PutObjectResult;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.result.ResultCodeEnum;
import com.atguigu.yygh.oss.service.FileService;
import com.atguigu.yygh.oss.utils.ConstantProperties;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Objects;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA
 *
 * @Date: 2023/1/3 - 16:55
 * @Author: Hyoung
 * @Description:
 */


@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private ConstantProperties constantProperties;

    @Override
    public String upload(MultipartFile file) {

        try {
            // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
            String endpoint = constantProperties.getEndpoint();
            // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
            String accessKeyId = constantProperties.getKeyId();
            String accessKeySecret = constantProperties.getKeySecret();
            String bucketName = constantProperties.getBucketName();


            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 判断目标bucket是否存在
            boolean doesBucketExist = ossClient.doesBucketExist(bucketName);
            if (!doesBucketExist) {
                ossClient.createBucket(bucketName);
                ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            }

            // 填写本地文件的完整路径。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
            InputStream inputStream = file.getInputStream();
            // 依次填写Bucket名称（例如examplebucket）和Object完整路径（例如exampledir/exampleobject.txt）。Object完整路径中不能包含Bucket名称。

            //构建日期路径：2019/02/26/
            String folder = new DateTime().toString("yyyy/MM/dd/");
            //文件名：uuid.扩展名
            String fileName = UUID.randomUUID().toString();
            String originalFilename = file.getOriginalFilename();
            String fileExtension = Objects.requireNonNull(originalFilename).substring(originalFilename.lastIndexOf("."));
            // TODO 限制文件格式
            if ("png".equalsIgnoreCase(fileExtension) || "jpg".equalsIgnoreCase(fileExtension) || "jpeg".equalsIgnoreCase(fileExtension)) {
                throw new YyghException(ResultCodeEnum.UNSUPPORTED_FILE_FORMAT);
            }
            String key = folder + fileName + fileExtension;
            PutObjectResult putObjectResult = ossClient.putObject(bucketName, key, inputStream);
//            String uri = putObjectResult.getResponse().getUri();
            // 关闭OSSClient。
            ossClient.shutdown();
//            return uri;
            //返回url地址
            return "https://" + bucketName + "." + endpoint + "/" + key;
        } catch (IOException e) {
            throw new YyghException(20017, "文件上传失败", e);
        }
    }
}